<?php
namespace App\Api\Controllers\DuoLaBao;


use App\Api\Controllers\Config\WeixinConfigController;
use App\Common\Log;
use App\Common\PaySuccessAction;
use App\Models\DlbConfig;
use App\Models\DlbStore;
use App\Models\Order;
use App\Models\OrderItem;
use App\Models\Store;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Log as Logger;

class ManageController extends BaseController
{

    public function test()
    {
        $timestamp = time();
        $orderno = date('YmdHis') . (str_pad(rand(0, 10000), 5, STR_PAD_LEFT));
        $total_fee = 1;//分
        $data = array(
            "agentNum" => $this->agentNum,
            "customerNum" => $this->mchNum,
            "shopNum" => $this->shopNum,
            "requestNum" => $orderno,
            "amount" => $total_fee / 100,
            "bankType" => 'WX',
            "authId" => 'safasdfsafsadfas',
            "callbackUrl" => $this->callbackUrl
        );
        $token = $this->dlb_sign($timestamp, $this->dlb_createorder_path, $data);
        $header = array(
            "Content-Type" => "application/json",
            "accessKey" => $this->accessKey,
            "timestamp" => $timestamp,
            "token" => $token,
        );
        $result = $this->post_func($this->dlb_host_url . $this->dlb_createorder_path, $data, $header);
        if ($result['status'] == 1) {
            $data = json_decode($result['data'], true);
            if (isset($data['error'])) {
                $result = ['status' => 0, 'message' => $data['error']['errMsg']];
            } else {
                dd($result);
            }
        }
        return $result;
    }


    public function pay($params)
    {
        $timestamp = time();
        $access_key = $params['accessKey'];
        $secret_key = $params['secretKey'];
        unset($params['accessKey']);
        unset($params['secretKey']);
        $token = $this->dlb_sign($timestamp, $this->dlb_createorder_path, $params, $secret_key);
        $header = array(
            "Content-Type" => "application/json",
            "accessKey" => $access_key,
            "timestamp" => $timestamp,
            "token" => $token,
        );
        $result = $this->post_func($this->dlb_host_url . $this->dlb_createorder_path, $params, $header);
        if ($result['status'] == 1) {

            $data = json_decode($result['data'], true);
//            Logger::info('哆啦宝支付结果');
//            Logger::info($data);
            if (isset($data['error'])) {
                $msg = "服务器繁忙，支付调用失败!";
                $msg .= isset($data['error']['errorCode']) ? $data['error']['errorCode'] : '';
                $msg .= isset($data['error']['errorMsg']) ? $data['error']['errorMsg'] : '';

                $result = ['status' => 0, 'message' => $msg];
            } else {
                if ($data['result'] == 'success') {
                    $bankRequest = $data['data']['bankRequest'];
                    $result = ['status' => 1, 'data' => $bankRequest];
                } elseif ($data['result'] == 'fail') {
                    $msg = "订单支付创建失败!";
                    $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                    $result = ['status' => 0, 'message' => $msg];
                } elseif ($data['result'] == 'error') {
                    $msg = "服务器繁忙，支付调用失败!";
                    $result = ['status' => 0, 'message' => $msg];
                } else {
                    $result = ['status' => 0, 'message' => '系统异常!'];
                }
            }
        }
        return $result;
    }


    public function pay_notify(Request $request)
    {
        try {
            $token = $request->header('token');
            $timestamp = $request->header('timestamp');
            $data = $request->only('requestNum', 'orderNum', 'orderAmount', 'status', 'completeTime', 'extraInfo');
            if ($data) {
                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $data['requestNum'])->first();

                } else {
                    $order = Order::where('out_trade_no', $data['requestNum'])->first();
                }

                if (!$order) {
                    return '';
                }
                $config_id = $order->config_id;//平台秘钥验签
                $dlbconfig = DlbConfig::where('config_id', $config_id)->first();
                if (!$dlbconfig) {
                    $dlbconfig = DlbConfig::where('config_id', '1234')->first();
                }
                $sign = strtoupper(sha1('secretKey=' . $dlbconfig->secret_key . '&timestamp=' . $timestamp));
                if ($sign == $token) {
                    if ($data['status'] != $order->status) {
                        if ($order->pay_status != 1) {
                            $update_data = [
                                'status' => '1',
                                'pay_status' => 1,
                                'pay_status_desc' => '支付成功',
                                'trade_no' => $data['orderNum'],
                                'pay_time' => $data['completeTime'],
                                'buyer_pay_amount' => $data['orderAmount']
                            ];


                           $this->update_day_order($update_data,$data['requestNum']);

                            if (strpos($order->out_trade_no, 'scan')) {


                            } else {
                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '15000',//返佣来源
                                    'source_desc' => '哆啦宝',//返佣来源说明
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'other_no' => $order->other_no,
                                    'rate' => $order->rate,
                                    'company' => $order->company,
                                    'fee_amount' => $order->fee_amount,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $order->config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $data['completeTime'],
                                    'device_id' => $order->device_id,
                                ];


                                PaySuccessAction::action($data);
                            }


                        }
                    }
                }
            }
        } catch (\Exception $e) {
            Log::write($e->getMessage() . $e->getLine(), 'dlb_qr.err');
        }
        return 'FAIL';
    }


    public function query_bill($params)
    {
        $timestamp = time();
        $get_param = "/" . $params["agentNum"] . "/" . $params["customerNum"] . "/" . $params["shopNum"] . "/" . $params["requestNum"];
        $token = $this->dlb_sign($timestamp, $this->dlb_queryorder_path . $get_param, [], $params['secretKey']);

        $header = array(
            "accessKey" => $params['accessKey'],
            "timestamp" => $timestamp,
            "token" => $token,
        );

        $result = $this->post_func($this->dlb_host_url . $this->dlb_queryorder_path . $get_param, '', $header, 10, 1);

        if ($result['status'] == 1) {
            $data = json_decode($result['data'], true);
            if (isset($data['error'])) {
                $msg = "服务器繁忙，支付订单查询失败!";
                $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                $result = ['status' => 0, 'message' => $msg];
            } else {
                if ($data['result'] == 'success') {
                    $result = ['status' => 1, 'data' => $data['data']];
                } elseif ($data['result'] == 'fail') {
                    $msg = "订单支付创建失败!";
                    $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                    $result = ['status' => 0, 'message' => $msg];
                } elseif ($data['result'] == 'error') {
                    $msg = "服务器繁忙，支付调用失败!";
                    $result = ['status' => 0, 'message' => $msg];
                } else {
                    $result = ['status' => 0, 'message' => '系统异常!'];
                }
            }
        }
        return $result;
    }


    public function pay_config($config_id)
    {
        //配置取缓存
        $config = DlbConfig::where('config_id', $config_id)->first();
        if (!$config) {
            $config = DlbConfig::where('config_id', '1234')->first();
        }

        return $config;
    }


    public function pay_url($params)
    {
        $timestamp = time();
        $access_key = $params['accessKey'];
        $secret_key = $params['secretKey'];
        unset($params['accessKey']);
        unset($params['secretKey']);
        $token = $this->dlb_sign($timestamp, $this->dlb_payurlorder_path, $params, $secret_key);
        $header = array(
            "Content-Type" => "application/json",
            "accessKey" => $access_key,
            "timestamp" => $timestamp,
            "token" => $token,
        );
        $result = $this->post_func($this->dlb_host_url . $this->dlb_payurlorder_path, $params, $header);
        if ($result['status'] == 1) {
            $data = json_decode($result['data'], true);
            if (isset($data['error'])) {
                $msg = "服务器繁忙，支付调用失败!";
                $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                $result = ['status' => 0, 'message' => $msg];
            } else {
                if ($data['result'] == 'success') {
                    $payurl = $data['data']['url'];
                    $result = ['status' => 1, 'url' => $payurl];
                } elseif ($data['result'] == 'fail') {
                    $msg = "订单支付创建失败!";
                    $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                    $result = ['status' => 0, 'message' => $msg];
                } elseif ($data['result'] == 'error') {
                    $msg = "服务器繁忙，支付调用失败!";
                    $result = ['status' => 0, 'message' => $msg];
                } else {
                    $result = ['status' => 0, 'message' => '系统异常!'];
                }
            }
        }
        return $result;
    }


    public function pay_scan($params)
    {
        $timestamp = time();
        $access_key = $params['accessKey'];
        $secret_key = $params['secretKey'];
        unset($params['accessKey']);
        unset($params['secretKey']);
        $token = $this->dlb_sign($timestamp, $this->dlb_scanorder_path, $params, $secret_key);

        $header = array(
            "Content-Type" => "application/json",
            "accessKey" => $access_key,
            "timestamp" => $timestamp,
            "token" => $token,
        );
        $result = $this->post_func($this->dlb_host_url . $this->dlb_scanorder_path, $params, $header);
        if ($result['status'] == 1) {
            $data = json_decode($result['data'], true);
            if (isset($data['error'])) {
                $msg = "服务器繁忙，支付调用失败!";
                $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                $result = ['status' => 0, 'message' => $msg];
            } else {
                if ($data['result'] == 'success') {
                    $result = ['status' => 1, 'data' => $data['data']];
                } elseif ($data['result'] == 'fail') {
                    $msg = "订单支付创建失败!";
                    $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                    $result = ['status' => 0, 'message' => $msg];
                } elseif ($data['result'] == 'error') {
                    $msg = "服务器繁忙，支付调用失败!";
                    $result = ['status' => 0, 'message' => $msg];
                } else {
                    $result = ['status' => 0, 'message' => '系统异常!'];
                }
            }
        }
        return $result;
    }


    public function pay_refund($params)
    {
        $timestamp = time();
        $access_key = $params['accessKey'];
        $secret_key = $params['secretKey'];
        unset($params['accessKey']);
        unset($params['secretKey']);
        if (isset($params['refundPartAmount']) && $params['refundPartAmount'] > 0) {
            $url_path = $this->dlb_refund_part_path;
        } else {
            $url_path = $this->dlb_refund_path;
        }
        $token = $this->dlb_sign($timestamp, $url_path, $params, $secret_key);

        $header = array(
            "Content-Type" => "application/json",
            "accessKey" => $access_key,
            "timestamp" => $timestamp,
            "token" => $token,
        );
        $result = $this->post_func($this->dlb_host_url . $url_path, $params, $header);
        if ($result['status'] == 1) {
            $data = json_decode($result['data'], true);
            if (isset($data['error'])) {
                $msg = "服务器繁忙，订单退款调用失败!";
                $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                $result = ['status' => 0, 'message' => $msg];
            } else {
                if ($data['result'] == 'success') {
                    Log::write($data, 'dlb_refund.txt');
                    $result = ['status' => 1, 'data' => $data['data']];
                } elseif ($data['result'] == 'fail') {
                    $msg = "退款失败!";
                    $msg .= isset($data['error']['errMsg']) ? $data['error']['errMsg'] : '';
                    $result = ['status' => 0, 'message' => $msg];
                } elseif ($data['result'] == 'error') {
                    $msg = "服务器繁忙，退款调用失败!";
                    $result = ['status' => 0, 'message' => $msg];
                } else {
                    $result = ['status' => 0, 'message' => '系统异常!'];
                }
            }
        }
        return $result;
    }


    public function dlb_merchant($store_id, $store_pid)
    {
        if ($store_pid) {
            //分店配置
            $merchant = DlbStore::where('store_id', $store_id)->first();
            if (!$merchant) {
                $store_pid_id = '';
                $store_p = Store::where('id', $store_pid)
                    ->select('store_id')
                    ->first();

                if ($store_p) {
                    $store_pid_id = $store_p->store_id;
                }

                $merchant = DlbStore::where('store_id', $store_pid_id)->first();
            }


        } else {
            $merchant = DlbStore::where('store_id', $store_id)->first();
        }

        return $merchant;
    }


}
